<template>
  <div class="wrapper">
    <!-- 顶部导航 -->
    <header class="page-header">
      <p>个人中心</p>
    </header>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <!-- 用户信息卡片 -->
      <div class="user-card">
        <div class="avatar-section">
          <img :src="userAvatar" alt="用户头像" class="avatar">
        </div>
        <div class="info-section">
          <div class="name-row">
            <h3 class="username" @click="handleAuthClick">
              {{ isLoggedIn ? userInfo.username : '注册/登录' }}
            </h3>
            <span class="user-tag" v-if="isLoggedIn">普通用户</span>
          </div>
          <p class="real-name" v-if="isLoggedIn">
            {{ (userInfo.lastName || '') + (userInfo.firstName || '') || '未填写真实姓名' }}
          </p>
        </div>
      </div>

      <!-- 详细信息列表 - 仅登录后显示 -->
      <div class="info-card" v-if="isLoggedIn">
        <div class="info-item">
          <span class="label">性别</span>
          <span class="value">{{ userInfo.gender || '未设置' }}</span>
        </div>
        <div class="info-item">
          <span class="label">手机号</span>
          <span class="value">{{ userInfo.phone || '未绑定' }}</span>
        </div>
        <div class="info-item">
          <span class="label">邮箱</span>
          <span class="value">{{ userInfo.email || '未绑定' }}</span>
        </div>
      </div>

      <!-- 功能操作区 -->
      <div class="function-card">
        <div class="function-item" @click="handleFunctionClick('changePwd')">
          <span>更改密码</span>
          <i class="fa fa-chevron-right"></i>
        </div>
        <div class="function-item" @click="handleFunctionClick('addressManage')">
          <span>地址管理</span>
          <i class="fa fa-chevron-right"></i>
        </div>
		<div class="function-item" @click="handleLogout" v-if="isLoggedIn">
		  <span style="color: #ff4d4f;">退出登录</span>
		  <i class="fa fa-sign-out" style="color: #ff4d4f;"></i>
		</div>
      </div>

      <!-- 未登录提示 -->
      <div class="login-tip" v-if="!isLoggedIn">
        <p>请先登录以使用完整功能</p>
      </div>
    </main>

    <!-- 密码修改弹窗 - 仅登录后显示 -->
    <div v-if="showPwdModal && isLoggedIn" class="modal-overlay" @click.self="showPwdModal = false">
      <div class="modal">
        <div class="modal-header">
          <h4>更改密码</h4>
          <i class="fa fa-times close-btn" @click="showPwdModal = false"></i>
        </div>
        <div class="modal-body">
          <div class="input-field">
            <input type="text" v-model="oldPwd" placeholder="请输入用户名">
          </div>
          <div class="input-field">
            <input type="password" v-model="newPwd" placeholder="请输入6-16位新密码">
          </div>
          <div class="input-field">
            <input type="password" v-model="confirmPwd" placeholder="请确认新密码">
          </div>
        </div>
        <div class="modal-actions">
          <button class="btn-secondary" @click="showPwdModal = false">取消</button>
          <button class="btn-primary" @click="confirmChangePwd">确认修改</button>
        </div>
      </div>
    </div>

    <!-- 底部导航 -->
    <Footer />
  </div>
</template>

<script>
import Footer from '../components/Footer.vue';

export default {
  name: 'UserCenter',
  components: {
    Footer,
  },
  data() {
    return {
      showPwdModal: false,
      oldPwd: '',
      newPwd: '',
      confirmPwd: '',
      userInfo: {}
    }
  },
  computed: {
     isLoggedIn() {
        // 改为从localStorage读取user
        const storedUser = this.$getLocalStorage('user');
        return !!storedUser;
      },
      userAvatar() {
        // 改为从localStorage读取user
        const storedUser = this.$getLocalStorage('user') || {};
        return storedUser.userImg || require('@/assets/nobody.jpg');
      }
		},
  mounted() {
    this.loadUserInfo();
  },
  methods: {
	  handleLogout() {
	      // 1. 改为清除localStorage中的用户信息
	      this.$removeLocalStorage('user');
	      // 2. 重新加载用户信息（重置userInfo和isLoggedIn状态）
	      this.loadUserInfo();
	      // 3. 跳转到登录页（可选，根据需求调整）
	      this.$router.push('/login');
	      // 4. 提示用户（可选）
	      alert('已成功退出登录');
	    },
    loadUserInfo() {
        // 改为从localStorage读取user
        const storedUser = this.$getLocalStorage('user');
        if (storedUser) {
          this.userInfo = storedUser;
        } else {
          this.userInfo = {};
        }
      },
    // 处理认证点击（用户名点击事件）
    handleAuthClick() {
      if (!this.isLoggedIn) {
        this.$router.push('/login');
      }
    },

    // 处理功能按钮点击
    handleFunctionClick(functionType) {
      if (!this.isLoggedIn) {
        this.$router.push('/login');
        return;
      }

      if (functionType === 'changePwd') {
        this.handleChangePwd();
      } else if (functionType === 'addressManage') {
        this.handleAddressManage();
      }
    },

    handleChangePwd() {
      this.oldPwd = '';
      this.newPwd = '';
      this.confirmPwd = '';
      this.showPwdModal = true;
    },

   confirmChangePwd() {
     if (!this.oldPwd) {
       alert('请输入用户名');
       return;
     }
     if (this.newPwd.length < 6 || this.newPwd.length > 16) {
       alert('新密码需为6-16位');
       return;
     }
     if (this.newPwd !== this.confirmPwd) {
       alert('两次输入密码不一致');
       return;
     }
   
     // 修改密码API调用 - 根据API文档调整
     this.$axios.post('/api/password', {
       username: this.oldPwd, // 使用oldPwd变量存储的用户名
       password: this.newPwd, // 新密码
       rememberMe: true // 根据API文档，需要包含rememberMe字段
     }, {
       headers: {
         'Content-Type': 'application/json' // 明确指定JSON格式
       }
     }).then(response => {
       if (response.status === 200) {
         alert('密码修改成功');
         this.showPwdModal = false;
         // 如果修改的是当前登录用户的密码，需要重新登录
         if (this.oldPwd === this.userInfo.username) {
           this.$removeLocalStorage('user');
           this.$router.push('/login');
         }
       } else {
         alert('密码修改失败');
       }
     }).catch(error => {
       console.error('修改失败:', error);
       if (error.response && error.response.status === 401) {
         alert('权限不足，只能修改自己的密码');
       } else {
         alert('网络异常');
       }
     });
   },
    handleAddressManage() {
      this.$router.push('/userAddress');
    }
  }
}
</script>

<style scoped>
.wrapper {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.page-header {
  height: 12vw;
  background: #0097FF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 4.8vw;
  position: sticky;
  top: 0;
  z-index: 100;
}

.main-content {
  flex: 1;
  padding: 4vw;
  padding-bottom: 18vw;
}

.user-card {
  background: white;
  border-radius: 12px;
  padding: 4vw;
  display: flex;
  align-items: center;
  gap: 3vw;
  margin-bottom: 3vw;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.avatar-section {
  width: 20vw;
  height: 20vw;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.info-section {
  flex: 1;
}

.name-row {
  display: flex;
  align-items: center;
  gap: 2vw;
  margin-bottom: 1vw;
}

.username {
  font-size: 4vw;
  color: #333;
  font-weight: 600;
  cursor: pointer;
}

.username:hover {
  color: #0097FF;
}

.user-tag {
  background: #38CA73;
  color: white;
  padding: 0.5vw 2vw;
  border-radius: 12px;
  font-size: 2.8vw;
}

.real-name {
  font-size: 3.2vw;
  color: #666;
}

.info-card,
.function-card {
  background: white;
  border-radius: 12px;
  margin-bottom: 3vw;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.info-item,
.function-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 3.5vw 4vw;
  border-bottom: 1px solid #eee;
}

.info-item:last-child,
.function-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 3.2vw;
  color: #333;
}

.value {
  font-size: 3.2vw;
  color: #666;
}

.function-item {
  cursor: pointer;
}

.function-item span {
  font-size: 3.2vw;
  color: #333;
}

.function-item i {
  color: #999;
  font-size: 3.2vw;
}

.login-tip {
  text-align: center;
  padding: 4vw;
  color: #999;
  font-size: 3.2vw;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12px;
  width: 80%;
  max-width: 400px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4vw;
  border-bottom: 1px solid #eee;
}

.modal-header h4 {
  font-size: 4vw;
  color: #333;
  font-weight: 600;
}

.close-btn {
  color: #999;
  cursor: pointer;
  font-size: 4vw;
}

.modal-body {
  padding: 4vw;
  box-sizing: border-box;
}

.input-field {
  margin-bottom: 3vw;
}

.input-field input {
  width: 100%;
  padding: 3vw;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 3.2vw;
  outline: none;
  box-sizing: border-box;
}

.input-field input:focus {
  border-color: #0097FF;
}

.modal-actions {
  display: flex;
  gap: 2vw;
  padding: 0 4vw 4vw;
}

.modal-actions button {
  flex: 1;
  padding: 3vw;
  border: none;
  border-radius: 6px;
  font-size: 3.2vw;
  cursor: pointer;
}

.btn-secondary {
  background: #f5f5f5;
  color: #666;
}

.btn-primary {
  background: #38CA73;
  color: white;
}
</style>